import { defHttp } from '/@/utils/http/axios';
import { AclInfo, RoleMenuSaveParam, AclSaveByModuleParam } from "/@/api/privilege/model/aclModel";
import { ModuleInfo } from "/@/api/privilege/model/moduleModel";
import { forEach, listToTree } from "/@/utils/helper/treeHelper";

enum Api {
  SetAcl = '/privilege/rolemenu/setAcl',
  getMenuList = '/privilege/rolemenu/getMenu',
  SetAllAcl = '/privilege/rolemenu/setAllAcl',
  setMenu = '/privilege/rolemenu/setMenu',
  SetAclByModule = '/privilege/rolemenu/setAclByModule',
}

// 根据角色id获取角色权限
export const getMenuList = (params: any) => {
  const result = defHttp.get<ModuleInfo>({ url: Api.getMenuList + "/" + params.roleId });
  return Promise.resolve(result).then((res: any) => {
    const treeData = listToTree(res, { id: 'id', children: 'children', pid: 'pid' });
    forEach(treeData, (node) => {
      if (node.children.length === 0) {
        delete node.children;
      }
    }, { id: 'id', children: 'children', pid: 'pid' });
    return treeData;
  });
};

// 设置角色权限
export const setAcl = (params: AclSaveByModuleParam) =>
  defHttp.post<AclInfo>({ url: Api.SetAcl + '/' + params.position + '/' + params.checked, params: params.aclInfo });

export const setAllAcl = (params: AclSaveByModuleParam) =>
  defHttp.post<AclInfo>({ url: Api.SetAllAcl + `/${params.checked}`, params: params.aclInfo });

export const setAclByModule = (params: AclSaveByModuleParam) =>
  defHttp.post<AclInfo>({ url: Api.SetAclByModule + '/' + params.checked, params: params.aclInfo });

export const setMenu = (params: RoleMenuSaveParam) =>
  defHttp.post<AclInfo>({ url: Api.setMenu, params: params });
